import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/blueprint/badge_print.dart';
import 'package:thal/backstage/control_room/badge_room.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/toolkit/widgets/stage_whisper.dart';

part 'badge_wall_production.page.dart';

/// 徽章墙页面
@PagePath('/badge-wall')
class BadgeWallProduction extends StatefulWidget {
  const BadgeWallProduction({super.key});

  @pageRouteQuery
  static RouteQuery query() => const _$BadgeWallProductionQuery().call();

  @override
  State<BadgeWallProduction> createState() => _BadgeWallProductionState();
}

class _BadgeWallProductionState extends State<BadgeWallProduction>
    with SingleTickerProviderStateMixin {
  String? _selectedBadgeId;
  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: Duration(seconds: 2),
      vsync: this,
    )..repeat();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.badgeBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          top: false,
          child: Observer(
            builder: (_) {
              final badgeRoom = GlobalStateProvider.badgeRoomOf(context);
              final userRoom = GlobalStateProvider.userRoomOf(context);
              final currentUser = userRoom.fetchCurrentUser();

              if (currentUser == null) {
                return _assembleEmptyState(context);
              }

              final allBadges = badgeRoom.fetchAllBadges();
              final userBadges = badgeRoom.fetchUserBadges(currentUser.id);
              final userBadgeIds = userBadges.map((ub) => ub.badgeId).toList();

              // 默认选中第一个勋章
              if (_selectedBadgeId == null && allBadges.isNotEmpty) {
                _selectedBadgeId = allBadges[0].id;
              }

              final selectedBadge = allBadges.firstWhere(
                (b) => b.id == _selectedBadgeId,
                orElse: () => allBadges[0],
              );
              final hasSelectedBadge = userBadgeIds.contains(_selectedBadgeId);

              return Stack(
                clipBehavior: Clip.none,
                children: [
                  Column(
                    children: [
                      56.h.heightBox,
                      // 顶部导航栏
                      _assembleHeader(context),

                      40.h.heightBox,

                      // 标题和进度
                      _assembleTitleAndProgress(
                        context,
                        userBadgeIds.length,
                        allBadges.length,
                      ),

                      20.h.heightBox,

                      // 主要内容区域
                      Expanded(
                        child: _assembleBadgeGrid(
                          context,
                          allBadges,
                          userBadgeIds,
                          badgeRoom,
                          currentUser.id,
                        ),
                      ),

                      40.h.heightBox,

                      // 底部按钮
                      _assembleActionButton(context, _selectedBadgeId),

                      40.h.heightBox,
                    ],
                  ),

                  // 右上角展示的勋章（相对于整个屏幕）
                  _assembleFeaturedBadge(
                    context,
                    selectedBadge,
                    hasSelectedBadge,
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  /// 组装空状态
  Widget _assembleEmptyState(BuildContext context) {
    return Center(
      child:
          Text(
            'Please login to view badges',
          ).fontSize(16.sp).textColor(ColorPalette.black).arimo(),
    );
  }

  /// 组装顶部导航栏
  Widget _assembleHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.white.withValues(alpha: 0.5),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chevron_left_rounded,
                color: ColorPalette.black,
                size: 36.sp,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 组装标题和进度
  Widget _assembleTitleAndProgress(
    BuildContext context,
    int earnedCount,
    int totalCount,
  ) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('Badge Wall')
              .fontSize(32.sp)
              .textColor(ColorPalette.black)
              .carterOne(weight: FontWeight.w700),
          8.h.heightBox,
          Row(
            children: [
              Text(
                'Accumulate ',
              ).fontSize(16.sp).textColor(ColorPalette.black).arimo(),
              Text('$earnedCount')
                  .fontSize(20.sp)
                  .textColor(ColorPalette.blue1)
                  .arimo(weight: FontWeight.w700),
              Text(
                ' Badges',
              ).fontSize(16.sp).textColor(ColorPalette.black).arimo(),
            ],
          ),
        ],
      ),
    );
  }

  /// 组装勋章网格
  Widget _assembleBadgeGrid(
    BuildContext context,
    List<BadgePrint> allBadges,
    List<String> userBadgeIds,
    BadgeRoom badgeRoom,
    String userId,
  ) {
    return Padding(
      padding: EdgeInsets.only(top: 40.h, left: 24.w, right: 24.w),
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: 16.h,
          crossAxisSpacing: 16.w,
          childAspectRatio: 0.85,
        ),
        itemCount: allBadges.length,
        itemBuilder: (context, index) {
          final badge = allBadges[index];
          final hasBadge = userBadgeIds.contains(badge.id);
          final isSelected = _selectedBadgeId == badge.id;

          return _constructBadgeItem(
            context,
            badge,
            hasBadge,
            isSelected,
            badgeRoom,
            userId,
          );
        },
      ),
    );
  }

  /// 构造勋章项
  Widget _constructBadgeItem(
    BuildContext context,
    BadgePrint badge,
    bool hasBadge,
    bool isSelected,
    BadgeRoom badgeRoom,
    String userId,
  ) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedBadgeId = badge.id;
        });
      },
      child: Column(
        children: [
          // 勋章容器
          Container(
            width: double.infinity,
            height: 100.w,
            decoration: BoxDecoration(
              color: hasBadge ? Colors.transparent : Colors.transparent,
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Stack(
              alignment: Alignment.center,
              children: [
                // 选中的高亮圆圈
                if (isSelected)
                  Container(
                    width: 88.w,
                    height: 88.w,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.white.withValues(alpha: 0.50),
                    ),
                  ),

                // 勋章图片
                SizedBox(
                  width: 70.w,
                  height: 70.w,
                  child: ColorFiltered(
                    colorFilter:
                        hasBadge
                            ? ColorFilter.matrix(<double>[
                              1, 0, 0, 0, 0, // R
                              0, 1, 0, 0, 0, // G
                              0, 0, 1, 0, 0, // B
                              0, 0, 0, 1, 0, // A
                            ])
                            : ColorFilter.matrix(<double>[
                              0.2126, 0.7152, 0.0722, 0, 0, // 灰度转换
                              0.2126, 0.7152, 0.0722, 0, 0,
                              0.2126, 0.7152, 0.0722, 0, 0,
                              0, 0, 0, 1, 0,
                            ]),
                    child: Image.asset(badge.imageUrl, fit: BoxFit.contain),
                  ),
                ),
              ],
            ),
          ),

          // 勋章名称
          Text(badge.name, textAlign: TextAlign.center)
              .fontSize(12.sp)
              .textColor(ColorPalette.black)
              .carterOne(weight: FontWeight.w400),
        ],
      ),
    );
  }

  /// 组装右上角展示的勋章
  Widget _assembleFeaturedBadge(
    BuildContext context,
    BadgePrint badge,
    bool hasBadge,
  ) {
    // 计算盒子尺寸：宽高比 170 / 276
    final boxWidth = 170.w;
    final boxHeight = boxWidth * (276 / 170);

    return Positioned(
      top: 0,
      right: 6.w,
      child: Container(
        width: boxWidth,
        height: boxHeight,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.showBackground),
            fit: BoxFit.fill,
          ),
        ),
        child: Stack(
          alignment: Alignment.bottomCenter,
          children: [
            // 勋章
            SizedBox(
              width: boxWidth * 0.65,
              height: boxWidth * 0.65,
              child: ColorFiltered(
                colorFilter:
                    hasBadge
                        ? ColorFilter.matrix(<double>[
                          1, 0, 0, 0, 0, // R
                          0, 1, 0, 0, 0, // G
                          0, 0, 1, 0, 0, // B
                          0, 0, 0, 1, 0, // A
                        ])
                        : ColorFilter.matrix(<double>[
                          0.2126, 0.7152, 0.0722, 0, 0, // 灰度转换
                          0.2126, 0.7152, 0.0722, 0, 0,
                          0.2126, 0.7152, 0.0722, 0, 0,
                          0, 0, 0, 1, 0,
                        ]),
                child: Image.asset(badge.imageUrl, fit: BoxFit.contain),
              ),
            ).wrapBottom(40.h),
          ],
        ),
      ),
    );
  }

  /// 组装操作按钮
  Widget _assembleActionButton(BuildContext context, String? selectedBadgeId) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(vertical: 16.h),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [ColorPalette.blue2, ColorPalette.blue1],
          ),
          borderRadius: BorderRadius.circular(30.r),
        ),
        child: Text('Display', textAlign: TextAlign.center)
            .fontSize(18.sp)
            .textColor(ColorPalette.white)
            .arimo(weight: FontWeight.w600),
      ).withTapEffect(
        onTap: () {
          if (selectedBadgeId != null) {
            final badgeRoom = GlobalStateProvider.badgeRoomOf(context);
            final userRoom = GlobalStateProvider.userRoomOf(context);
            final currentUser = userRoom.fetchCurrentUser();

            if (currentUser != null) {
              // 检查用户是否拥有该勋章
              final hasBadge = badgeRoom.hasBadge(
                currentUser.id,
                selectedBadgeId,
              );

              if (hasBadge) {
                // 用户拥有该勋章，设置为展示并提示成功
                badgeRoom.setUserDisplayedBadge(
                  currentUser.id,
                  selectedBadgeId,
                );
                StageWhisper.cheer('Badge displayed successfully!');
                Navigator.of(context).pop();
              } else {
                // 用户还未获得该勋章，提示用户
                final selectedBadge = badgeRoom.fetchBadgeById(selectedBadgeId);
                StageWhisper.broadcast(
                  'You haven\'t earned the ${selectedBadge?.name ?? "Badge"} yet. Keep trying!',
                );
              }
            }
          }
        },
      ),
    );
  }
}
